const axios = require('axios');
const path = require('path');
const fs = require('fs');
const FormData = require('form-data');

const state = {
    config: null,
    localDir: process.cwd(),
    remoteDir: null,  // 登录后会设置为用户的根目录
    api: null
}

function createFileClient(config) {
    state.config = config;
    state.api = axios.create({
        baseURL: config.apiUrl,
        headers: {
            'Content-Type': 'application/json',
        }
    });
    return {
        login,
        listFiles,
        uploadFile,
        downloadFile,
        deleteItem,
        renameItem,
        createDirectory,
        changeLocalDir,
        changeRemoteDir,
        getLocalDir,
        getRemoteDir
    }
}

async function login() {
    try {
        const res = await state.api.post('/users/login', {
            username: state.config.username,
            password: state.config.password
        });
        const needRes = res.data;
        if (needRes.status === 1) {
            state.api.defaults.headers.common['Authorization'] = `Bearer ${needRes.data.token}`;
            state.remoteDir = needRes.data.remoteDir;  // 设置用户根目录
            return {ok:true,message:'登录成功'};
        } else {
            return {ok:false,message:'登录失败，请检查用户名和密码是否正确'};
        }
    } catch (error) {
        return '登录失败: ' + (error.response?.data?.message || error.message);
    }
}

async function listFiles() {
    try {
        const res = await state.api.get('/files/list', {
            params: { path: state.remoteDir }
        });
        const needRes = res.data;
        if (needRes.status === 1) {
            return needRes.data;
        } else {
            return '获取文件列表失败: ' + needRes.message;
        }
    } catch (error) {
        return '获取文件列表失败: ' + (error.response?.data?.message || error.message);
    }
}

async function uploadFile(filename) {
    const localFilePath = path.join(state.localDir, filename);
    if (!fs.existsSync(localFilePath)) {
        return '本地文件不存在';
    }

    try {
        const remoteFilePath = path.join(state.remoteDir, filename);
        const formData = new FormData();
        formData.append('file', fs.createReadStream(localFilePath));
        formData.append('path', remoteFilePath);

        const headers = {
            ...formData.getHeaders(),
            'Authorization': state.api.defaults.headers.common['Authorization']
        };

        const res = await state.api.post('/files/upload', formData, { headers });
        const needRes = res.data;
        if (needRes.status === 1) {
            return `上传成功,文件名:${filename}`;
        } else {
            return '上传失败: ' + (needRes.message || '');
        }
    } catch (error) {
        return '上传失败: ' + (error.response?.data?.message || error.message);
    }
}

async function downloadFile(filename) {
    try {
        // 构建完整的远程文件路径
        const remoteFilePath = path.join(state.remoteDir, filename).replace(/\\/g, '/');

        const res = await state.api.get('/files/download', {
            params: { 
                filepath: remoteFilePath
            },
            responseType: 'stream'
        });

        // 如果响应不成功，抛出错误
        if (!res.data || res.data.status === 0) {
            throw new Error(res.data?.message || '下载失败');
        }

        // 构建本地文件路径并创建写入流
        const localFilePath = path.join(state.localDir, filename);
        
        const cRootDirPattern = new RegExp(`^[cC]:\\\\${filename}$`, 'i');
        if (cRootDirPattern.test(localFilePath)) {
            throw new Error('您没有在C盘根目录下载的权限');
        }

        const writer = fs.createWriteStream(localFilePath);

        return new Promise((resolve, reject) => {
            res.data.pipe(writer);
            
            writer.on('finish', () => {
                resolve(`下载成功,文件名:${filename}`);
            });
            
            writer.on('error', (err) => {
                // 如果写入失败，删除部分下载的文件
                // fs.unlink(localFilePath).catch(() => {});
                reject('下载失败: ' + err.message);
            });
        });
    } catch (error) {
        console.error('Download error:', error.response?.data || error.message);
        return '下载失败: ' + (error.response?.data?.message || error.message);
    }
}

async function deleteItem(name) {
    try {
        const files = await listFiles();
        if (typeof files === 'string') {  // 如果返回错误消息
            return '删除失败: 无法获取文件列表';
        }
        const isDirectory = files.find(file => file.name === name)?.isDir || false;
        const remotePath = path.join(state.remoteDir, name);

        const res = await state.api.delete('/files/delete', {
            data: {
                path: remotePath,
                isDirectory
            }
        });
        const needRes = res.data;
        if (needRes.status === 1) {
            return '删除成功';
        } else {
            return '删除失败: ' + (needRes.message || '');
        }
    } catch (error) {
        return '删除失败: ' + (error.response?.data?.message || error.message);
    }
}

async function renameItem(oldName, newName) {
    try {
        const oldPath = path.join(state.remoteDir, oldName);
        const newPath = path.join(state.remoteDir, newName);

        const res = await state.api.put('/files/rename', {
            oldPath,
            newPath
        });
        const needRes = res.data;
        if (needRes.status === 1) {
            return '重命名成功';
        } else {
            return '重命名失败: ' + (needRes.message || '');
        }
    } catch (error) {
        return '重命名失败: ' + (error.response?.data?.message || error.message);
    }
}

async function createDirectory(name) {
    try {
        const remotePath = path.join(state.remoteDir, name);

        const res = await state.api.post('/files/mkdir', {
            path: remotePath
        });
        const needRes = res.data;
        if (needRes.status === 1) {
            return '创建目录成功';
        } else {
            return '创建目录失败: ' + (needRes.message || '');
        }
    } catch (error) {
        return '创建目录失败: ' + (error.response?.data?.message || error.message);
    }
}

async function changeLocalDir(dir) {
    if (!path.isAbsolute(dir)) {
        return '路径必须是绝对路径';
    }
    try {
        await fs.promises.access(dir);
        state.localDir = dir;
        return '切换本地目录成功';
    } catch (error) {
        return '本地目录不存在';
    }
}

async function changeRemoteDir(dir) {
    if (!path.isAbsolute(dir)) {
        return '路径必须是绝对路径';
    }
    if(dir.includes('/server/storage') || dir.includes('\\server\\storage')){
        const normalizedPath = path.normalize(dir).replace(/\\/g, '/');
        const regex = new RegExp(`^.*\/storage(?:\/${state.config.username}(?:\/.*)?)?\/?$`);
        if(!regex.test(normalizedPath)){
            return '您无权访问其他用户的根目录'
        }
    }
    // 验证目录是否存在
    try {
        const res = await state.api.get('/files/list', {
            params: { path: dir }
        });
        if (res.data.status === 1) {
            state.remoteDir = dir;
            return '切换远程目录成功';
        } else {
            return '远程目录不存在: ' + res.data.message;
        }
    } catch (error) {
        return '切换远程目录失败: ' + (error.response?.data?.message || error.message);
    }
}

function getLocalDir() {
    return state.localDir;
}

function getRemoteDir() {
    return state.remoteDir;
}

module.exports = createFileClient;

